package com.free.framework.lib.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.List;


/**
 * 自定义toast
 * author : sunny
 * email : zicai346@gmail.com
 * github : https://github.com/sunshinePrince
 * blog : http://mrjoker.wang
 */
public class CustomToast {

	private static Toast mToast;
	private static Handler mHandler = new Handler();
	private static Runnable r = new Runnable() {
		public void run() {
			mToast.cancel();
		}
	};

	private static WeakReference<Context> mContext;


	@SuppressLint("ShowToast")
	public static void initCustomToast(Context context) {
		if (null == mToast) {
			synchronized (CustomToast.class) {
				if (null == mToast) {
					mContext = new WeakReference<>(context);
					mToast = Toast.makeText(context,"",Toast.LENGTH_SHORT);
					mToast.setGravity(Gravity.CENTER, 0, 0);
				}
			}
		}
	}


	/**
	 * 显示toast,移除前一个提示,只在应用在前台的时候显示
	 *
	 * @param text     显示内容
	 * @param duration 显示时间
	 */
	public static void showToast(final String text, int duration) {
		if (TextUtils.isEmpty(text)) {
			return;
		}
		mHandler.removeCallbacks(r);
		int second = text.length() / 10 + 1;
		duration = Math.min(duration, second * 1000);
		mHandler.postDelayed(r, duration);
		Context context = mContext.get();
		if (null != context && isAppOnForeground(context)) {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					mToast.setText(text);
					mToast.show();
				}
			});
		}
	}


	public static void showToast(String text) {
		showToast(text, 2000);
	}

	public static void showToast(@StringRes int resId) {
		Context context = mContext.get();
		if (null != context) {
			String string = context.getResources().getString(resId);
			showToast(string, 2000);
		}
	}

	/**
	 * 判断应用程序是否在前台
	 *
	 * @param context
	 * @return
	 */
	public static boolean isAppOnForeground(Context context) {
		if (context == null) {
			return false;
		}
		ActivityManager activityManager = (ActivityManager) context.getSystemService(
				Context.ACTIVITY_SERVICE);
		String packageName = context.getPackageName();
		List<ActivityManager.RecentTaskInfo> appTask = activityManager.getRecentTasks(Integer.MAX_VALUE, 1);
		if (appTask == null || appTask.size() < 1) {
			return false;
		}
		if (appTask.get(0).baseIntent.toString().contains(packageName)) {
			return true;
		}
		return false;
	}


}
